<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  roomImageUpApi,
  insertShopLiveInfoApi,
  updateShopLiveAPi,
  getShopLiveByRoomId
} from "@/server/api/shopApi.js";
import { ToastFun } from "@/hook/toast";
import { showDialog } from 'vant';
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const route = useRoute();
const router = useRouter();

//酒店详情
const hotelDetails = reactive({
  adult: 1, //能住几个人1
  appliance: 12,
  basics: [
    /**基础设施 */
    {
      flag: true,
      name: "",
    },
  ],
  bath: 12,
  bed: null /** 几个床 */,
  bedType: "" /** 床型 */,
  children: null /**能住几个儿童 */,
  detail: "" /**房型描述 */,
  floor: "" /** 楼层 */,
  imageList: [] /**房型图片集合 0*/,
  inventory: null /**房型库存 */,
  isAdd: null /**是否允许加客 0:可以 1:不可以 */,
  land: null /**出租土地平方米 */,
  price: null /** 价格 */,
  restRoom: null /** 几间卫生间 */,
  restricted: "" /** 限制 0*/,
  room: null /** 几间房 */,
  roomTypeName: "" /** 房型名称 */,
  shopId: route.query.data /**所属实体店id */,
  tagList: [""] /**房型标签集合 */,
});

const roomId = ref(null)
const isAddShow = ref(false);
const piShow = ref(false);
const Addtext = ref("");
const piText = ref("");
const basicsShow = ref(false); //基础设施弹出层
const aaa = ref(1.111);
// 选择后的基础设施
const basicNewList = ref([]);
let initialReq = ref({});
const bathNewList = ref([])
const bathShow = ref(false)
const applianceNewList = ref([]) // 选择后的电设施 
const applianceShow = ref(false)
let imgList = ref([]); //图片展示
let imageUrls = ref([]);
const showBasics = ref("") //显示选择的基础设施
const showBath = ref("") //显示选择的淋浴设施
const showAppliance = ref("") //显示选择的电器设施

//所有的基础设施
const basicList = ref([
  {
    name: "24小时前台",
    img: "/images/Hotelpictures/24小时前台.svg",
    status: 0,
    flag: true,
  },
  {
    name: "安保人员",
    img: "/images/Hotelpictures/安保人员.svg",
    status: 0,
    flag: true,
  },
  {
    name: "安全报警器",
    img: "/images/Hotelpictures/安全报警器.svg",
    status: 0,
    flag: true,
  },
  {
    name: "餐厅",
    img: "/images/Hotelpictures/餐厅.svg",
    status: 0,
    flag: true,
  },
  {
    name: "电梯",
    img: "/images/Hotelpictures/电梯.svg",
    status: 0,
    flag: true,
  },
  {
    name: "多功能厅",
    img: "/images/Hotelpictures/多功能厅.svg",
    status: 0,
    flag: true,
  },
  {
    name: "会议厅",
    img: "/images/Hotelpictures/会议厅.svg",
    status: 0,
    flag: true,
  },
  {
    name: "叫车服务",
    img: "/images/Hotelpictures/叫车服务.svg",
    status: 0,
    flag: true,
  },
  {
    name: "禁烟",
    img: "/images/Hotelpictures/禁烟.svg",
    status: 0,
    flag: true,
  },
  {
    name: "快递服务",
    img: "/images/Hotelpictures/快递服务.svg",
    status: 0,
    flag: true,
  },
  {
    name: "礼宾服务",
    img: "/images/Hotelpictures/礼宾服务.svg",
    status: 0,
    flag: true,
  },
  {
    name: "灭火器",
    img: "/images/Hotelpictures/灭火器.svg",
    status: 0,
    flag: true,
  },
  {
    name: "叫醒服务",
    img: "/images/Hotelpictures/闹钟.svg",
    status: 0,
    flag: true,
  },
  {
    name: "送餐服务",
    img: "/images/Hotelpictures/送餐服务.svg",
    status: 0,
    flag: true,
  },
  {
    name: "火灾报警器",
    img: "/images/Hotelpictures/图标-地图-火灾报警器.svg",
    status: 0,
    flag: true,
  },

  {
    name: "无烟楼层",
    img: "/images/Hotelpictures/无烟楼层.svg",
    status: 0,
    flag: true,
  },

  {
    name: "行李寄存",
    img: "/images/Hotelpictures/行李寄存.svg",
    status: 0,
    flag: true,
  },
  {
    name: "烟雾报警器",
    img: "/images/Hotelpictures/烟雾报警器.svg",
    status: 0,
    flag: true,
  },
  {
    name: "专职行李员",
    img: "/images/Hotelpictures/专职行李员.svg",
    status: 0,
    flag: true,
  },
  {
    name: "公共停车场",
    img: "/images/Hotelpictures/dt-公共停车场.svg",
    status: 0,
    flag: true,
  },

  {
    name: "摄像头",
    img: "/images/Hotelpictures/kakoutongji.svg",
    status: 0,
    flag: true,
  },

]);

//洗沐设施 
const bathList = ref([
  {
    name: "洗衣服务",
    img: "/images/Hotelpictures/洗衣服务.svg",
    status: 0,
    flag: true,
  },
  {
    name: "热水",
    img: "/images/Hotelpictures/外送洗衣服务.svg",
    status: 0,
    flag: true,
  },
])

const applianceList = ref([
  {
    name: "wifi",
    img: "/images/Hotelpictures/wifi.svg",
    status: 0,
    flag: true,
  },
  {
    name: "公共音响系统",
    img: "/images/Hotelpictures/icon_公共音响系统.svg",
    status: 0,
    flag: true,
  },
])

const yesnoAdd = [
  { text: "是", value: 0 },
  { text: "否", value: 1 },
];
const piFlag = [
  { text: "是", value: 1 },
  { text: "否", value: 0 },
];



//提交的数据
const dto = ref({
  /**
    * 房型ID
    */
  roomId: "",
  /**
    * 房型名称
    */
  roomTypeName: "",

  /**
   * 所属实体店id
   */
  shopId: null,

  /**
   * 房型库存
   */
  inventory: 100,

  /**
   * 房型描述
   */
  detail: "大床房",



  /**
   * 房型图片集合
   */
  imageList: [],
  /**
   * 被删除的图片集合
   */
  deleteImageList: [],

  /**
   * 出租土地平方米
   */
  land: 1,

  /**
   * 几间房
   */
  room: 2,

  /**
   * 几间卫生间
   */
  restRoom: 1,

  /**
   * 几个床
   */
  bed: 1,

  /**
   * 能住几个成年人
   */
  adult: 2,

  /**
   * 能住几个儿童
   */
  children: 2,

  /**
   * 限制
   */
  restricted: "限制",
  /**
   * 价格
   */
  price: 100,

  /**
   * 床型
   */
  bedType: "单人间",

  /**
   * 楼层
   */
  floor: 20,

  /**
   * 是否允许加客 0:可以 1：不可以
   */
  isAdd: 1,
  /**
   * 是否允许PI币 0:不可以 1：可以
   */
  piFlag: 0,
  /**
  * 房型标签集合
  */
  tagList: [],

  /**
   * 基础设施
   */
  basics: [],

  /**
   * 洗沐设施
   */
  bath: [],

  /**
   * 电器设施
   */
  appliance: [],
})

const validateNumber = (val) => {
  if (isNaN(val)) {
    return "必须是数字";
  }
};

//确定是否允许加客
const confirmFs = ({ selectedOptions }) => {
  Addtext.value = selectedOptions[0].text;
  dto.value.isAdd = selectedOptions[0].value;
  isAddShow.value = false;
};
//确定是否允许加客
const confirmPi = ({ selectedOptions }) => {
  piText.value = selectedOptions[0].text;
  dto.value.piFlag = selectedOptions[0].value;
  piShow.value = false;
};

let rommImgListFiles = ref([]);
//实景图
const rommImg = async (files) => {
  if (!Array.isArray(files)) {
    files = [files];
    rommImgListFiles.value.push(...files);
  }
  else {
    rommImgListFiles.value.push(...files);
  }

};



const deleteImagsLis = (file, detail) => {
  rommImgListFiles.value = rommImgListFiles.value.filter(item => item.objectUrl !== file.objectUrl)
  const index = detail.index;
  if (index >= 0 && index < dto.value.imageList.length) {
    if (Array.isArray(dto.value.imageList)) {
      dto.value.imageList.splice(index, 1);
      console.log("删除后的图片列表：", dto.value.imageList);
    }
  } else {
    console.warn("无效的索引:", index);
  }
};


// 基础设施选择函数
const verifyBasics = () => {
  basicNewList.value = basicList.value
    .filter((item) => item.status == true && item.flag == true)
    .map(({ flag, name }) => ({ flag, name }));
  console.log(basicNewList.value)
  // 将 name 字段提取出来并连接成一个字符串
  showBasics.value = basicNewList.value
    .map(item => item.name)  // 提取 name 字段
    .join(", ");             // 用逗号和空格连接成字符串
  dto.value.basics = basicNewList.value;
  basicsShow.value = false;
  ToastFun(t("pay.success2"));
};

//淋浴
const verifyBath = () => {
  bathNewList.value = bathList.value
    .filter((item) => item.status == true && item.flag == true)
    .map(({ flag, name }) => ({ flag, name }));
  showBath.value = bathNewList.value
    .map(item => item.name)
    .join(", ");
  dto.value.bath = bathNewList.value;
  bathShow.value = false;
  ToastFun(t("pay.success2"));
}

//电器设施
const verifyAppliance = () => {
  applianceNewList.value = applianceList.value
    .filter((item) => item.status == true && item.flag == true)
    .map(({ flag, name }) => ({ flag, name }));
  showAppliance.value = applianceNewList.value
    .map(item => item.name)
    .join(", ");
  dto.value.appliance = applianceNewList.value;
  applianceShow.value = false;
  ToastFun(t("pay.success2"));
}

const imgUp = async () => {
  try {
    // 使用 map 遍历文件数组进行上传
    await Promise.all(rommImgListFiles.value.map(async (file) => {
      let formData = new FormData();
      formData.append("file", file.file);  // 假设 files 是包含文件对象的数组
      const res = await roomImageUpApi(formData);

      // 判断 dto.value.imageList 中是否已经有相同的图片
      const isDuplicate = dto.value.imageList.some(item => item === res.data.data);

      if (isDuplicate) {
        showDialog({
          title: '提示',
          message: '图片已存在',
        }).then(() => { });
        file.status = 'failed';
        file.message = '图片已存在';
        imgList.value = imgList.value.filter(item => item !== file);
      } else {
        // 如果没有重复，正常添加到 imageList
        dto.value.imageList.push(res.data.data);
      }

    }));
  } catch (error) {
    console.error("上传失败:", error);
  }
};
const findDeletedImages = () => {
  const deletedImages = [];
  const initialImages = initialReq.value.imageId || [];
  const updatedImages = dto.value.imageList || [];
  initialImages.forEach(imageId => {
    if (!updatedImages.includes(imageId)) {
      deletedImages.push(imageId);
    }
  });
  return deletedImages;
};
const onSubmit = async () => {
  if (imgList.value.length == 0) {
    ToastFun("show", { msg: t("me.PersonalPosting.shop.imgTips5") });
    return false;
  }
  if (!route.query.status) {
    await imgUp();
    const res = await insertShopLiveInfoApi(dto.value);
    if (res.data.code == 200) {
      ToastFun(t("pay.success2"));
      router.push({
        path: "/hotel",
      });
    }
  } else {
    await imgUp();
    // 处理删除图片
    const deletedImages = findDeletedImages();
    if (deletedImages.length > 0) {
      dto.value.deleteImageList = deletedImages;
    }
    const res = await updateShopLiveAPi(dto.value);
    if (res.data.code == 200) {
      ToastFun(t("pay.success2"));
      router.push({
        path: "/hotel",
      });
    }
  }

  // if (hotelDetails.imageList.length == 0) {
  //   let res = null;
  //   if (route.query.status) {
  //     hotelDetails.basics = JSON.stringify(hotelDetails.basics);
  //     hotelDetails.imageList = JSON.stringify(hotelDetails.imageList);
  //     hotelDetails.tagList = JSON.stringify(hotelDetails.tagList);
  //     res = await updateShopLiveAPi(hotelDetails);
  //   } else {
  //     res = await insertShopLiveInfoApi(hotelDetails);
  //   }
  //   console.log(res.data.code);
  //   if (res.data.code == 200) {
  //     ToastFun("success");
  //     hotelDetails = {
  //       adult: null, //能住几个人1
  //       appliance: [
  //         /**电器设施 */
  //         {
  //           flag: true,
  //           name: "",
  //         },
  //       ],
  //       basics: [
  //         /**基础设施 */
  //         {
  //           flag: true,
  //           name: "",
  //         },
  //       ],
  //       bath: [
  //         /**洗沐设施 */
  //         {
  //           flag: true,
  //           name: "",
  //         },
  //       ],
  //       bed: null /** 几个床 */,
  //       bedType: "" /** 床型 */,
  //       children: null /**能住几个儿童 */,
  //       detail: "" /**房型描述 */,
  //       floor: "" /** 楼层 */,
  //       imageList: [] /**房型图片集合 0*/,
  //       inventory: null /**房型库存 */,
  //       isAdd: null /**是否允许加客 0:可以 1:不可以 */,
  //       land: null /**出租土地平方米 */,
  //       price: null /** 价格 */,
  //       restRoom: null /** 几间卫生间 */,
  //       restricted: "" /** 限制 0*/,
  //       room: null /** 几间房 */,
  //       roomTypeName: "" /** 房型名称 */,
  //       shopId: route.query.data /**所属实体店id */,
  //       tagList: [""] /**房型标签集合 */,
  //     };
  //     router.back();
  //   } else {
  //     ToastFun("", { msg: "失败" });
  //   }
  // } else {
  //   ToastFun("", { msg: "失败" });
  // }

};



const getShopLiveByRoomIdInfo = async (roomId) => {
  const res = await getShopLiveByRoomId(roomId)
  initialReq.value = JSON.parse(JSON.stringify(res.data.data));
  console.log(res)
  // 从服务器响应的图片列表（假设是 URL）更新 imgList
  imageUrls = res.data.data.imageList.map(url => {
    return { url }; // 如果需要，可以将 URL 包装成图片对象
  });
  imgList.value.push(...imageUrls);
  dto.value.roomId = roomId
  dto.value.imageList = res.data.data.imageId
  dto.value.roomTypeName = res.data.data.roomTypeName
  dto.value.land = res.data.data.land
  dto.value.restricted = res.data.data.restricted
  dto.value.basics = res.data.data.basics
  showBasics.value = res.data.data.basics
    .map(item => item.name)
    .join(", ");
  dto.value.bath = res.data.data.bath
  showBath.value = res.data.data.bath
    .map(item => item.name)
    .join(", ");
  dto.value.appliance = res.data.data.appliance
  showAppliance.value = res.data.data.appliance
    .map(item => item.name)
    .join(", ");
  dto.value.price = res.data.data.price
  dto.value.restRoom = res.data.data.restRoom
  dto.value.bed = res.data.data.bed
  dto.value.adult = res.data.data.adult
  dto.value.children = res.data.data.children
  dto.value.floor = res.data.data.floor
  dto.value.bedType = res.data.data.bedType
  dto.value.room = res.data.data.room
  dto.value.isAdd = res.data.data.isAdd
  const match = yesnoAdd.find(item => item.value === res.data.data.isAdd);
  const matchPi = piFlag.find(item => item.value === res.data.data.isAdd);
  Addtext.value = match ? match.text : "";
  piText.value = matchPi ? matchPi.text : "";
}


onMounted(() => {
  if (route.query.status) {
    roomId.value = route.query.data
    console.log("修改酒店房间 ，房间id", route.query.data)
    getShopLiveByRoomIdInfo(roomId.value)
  } else {
    dto.value.shopId = route.query.data
    console.log("发布酒店房间 ，酒店id", route.query.data)
  }

})

</script>


<template>
  <div class="hotelMerchandise">
    <div class="back">
      <van-icon name="arrow-left" size="20" @click="$router.back()" />
    </div>
    <van-form @submit="onSubmit">
      <div class="imge">
        <p>房间的详情图片(必须上传)</p>
        <van-uploader v-model="imgList" preview-size="60px" :after-read="rommImg" :max-count="8" multiple
          @delete="deleteImagsLis" />
      </div>
      <van-cell-group inset style="margin: 0">

        <van-field v-model="dto.roomTypeName" name="roomTypeName" label="房型名称" placeholder="房型名称"
          :rules="[{ required: true, message: '不能为空' }]" />

        <van-field v-model="dto.inventory" name="inventory" label="房型库存" placeholder="房型库存"
          :rules="[{ validator: validateNumber }]" />

        <van-field v-model="dto.detail" name="detail" label="房型描述" placeholder="房型描述" />

        <van-field v-model="dto.land" name="land" label="出租土地㎡" placeholder="出租土地㎡"
          :rules="[{ validator: validateNumber }]" />

        <van-field v-model="dto.room" name="room" label="几间房" placeholder="几间房" />
        <van-field v-model="dto.restRoom" name="restRoom" label="几间卫生间" placeholder="几间卫生间"
          :rules="[{ validator: validateNumber }]" />

        <van-field v-model="dto.bed" name="bed" label="几个床" placeholder="几个床"
          :rules="[{ validator: validateNumber }]" />

        <van-field v-model="dto.adult" name="adult" label="能住几个成年人" placeholder="能住几个成年人"
          :rules="[{ validator: validateNumber }]" />

        <van-field v-model="dto.children" name="children" label="能住几个儿童" placeholder="能住几个儿童"
          :rules="[{ validator: validateNumber }]" />

        <!-- <van-field v-model="dto.bedType" name="bedType" label="限制" placeholder="限制" /> -->

        <van-field v-model="dto.price" name="price" label="价格" placeholder="价格ecny" :rules="[
          { validator: validateNumber, required: true, message: '不能为空' },
        ]" />
        <van-field v-model="dto.bedType" name="bedType" label="床型" placeholder="床型" />

        <van-field v-model="dto.floor" name="floor" label="楼层" placeholder="楼层"
          :rules="[{ required: true, message: '不能为空' }]" />

        <!-- <van-field
          v-model="hotelDetails.isAdd"
          name="isAdd"
          label="是否允许加客"
          placeholder="是否允许加客"
        /> -->
        <van-field v-model="Addtext" is-link readonly label="是否允许加客" placeholder="是否允许加客" @click="isAddShow = true" />
        //选择是否可以加客
        <van-popup v-model:show="isAddShow" round position="bottom">
          <van-picker :columns="yesnoAdd" @cancel="isAddShow = false" @confirm="confirmFs" />
        </van-popup>
        <van-field v-model="piText" is-link readonly label="Pi币" placeholder="是否允许使用Pi币" @click="piShow = true" />
        //选择是否可以用Pi币
        <van-popup v-model:show="piShow" round position="bottom">
          <van-picker :columns="piFlag" @cancel="piShow = false" @confirm="confirmPi" />
        </van-popup>
        <van-field v-model="dto.restricted" name="restricted" label="入住条件" placeholder="例子:仅能接受大陆身份证" />

        <van-field v-model="dto.tagList[0]" name="tagList" label="房型标签集合" placeholder="房型标签集合" />

        <van-field is-link readonly label="基础设施" v-model="showBasics" placeholder="基础设施" @click="basicsShow = true" />

        <!-- 基础设施弹窗 -->
        <van-popup v-model:show="basicsShow" round position="bottom" :style="{ height: '60%' }">
          <div class="basicsList">
            <div v-for="(i, index) in basicList" :key="index" @click="i.status = !i.status"
              :class="['item', i.status ? 'con' : '']">
              <div class="imges">
                <img :src="i.img" alt="" />
              </div>
              <p>{{ i.name }}</p>
              <van-icon name="success" color="#1a90bf" v-show="i.status" size="18px" />
            </div>
            <div class="btn">
              <div @click="verifyBasics">{{ $t("exchange.confirm") }}</div>
            </div>
          </div>
        </van-popup>


        <van-field is-link readonly label="洗沐设施" v-model="showBath" name="bath" placeholder="洗沐设施"
          @click="bathShow = true" />
        <van-popup v-model:show="bathShow" round position="bottom" :style="{ height: '60%' }">
          <div class="basicsList">
            <div v-for="(i, index) in bathList" :key="index" @click="i.status = !i.status"
              :class="['item', i.status ? 'con' : '']">
              <div class="imges">
                <img :src="i.img" alt="" />
              </div>
              <p>{{ i.name }}</p>
              <van-icon name="success" color="#1a90bf" v-show="i.status" size="18px" />
            </div>
            <div class="btn">
              <div @click="verifyBath">{{ $t("exchange.confirm") }}</div>
            </div>
          </div>
        </van-popup>

        <van-field is-link readonly label="电器设施" v-model="showAppliance" name="appliance" placeholder="电器设施"
          @click="applianceShow = true" />
        <van-popup v-model:show="applianceShow" round position="bottom" :style="{ height: '60%' }">
          <div class="basicsList">
            <div v-for="(i, index) in applianceList" :key="index" @click="i.status = !i.status"
              :class="['item', i.status ? 'con' : '']">
              <div class="imges">
                <img :src="i.img" alt="" />
              </div>
              <p>{{ i.name }}</p>
              <van-icon name="success" color="#1a90bf" v-show="i.status" size="18px" />
            </div>
            <div class="btn">
              <div @click="verifyAppliance">{{ $t("exchange.confirm") }}</div>
            </div>
          </div>
        </van-popup>


      </van-cell-group>



      <!-- <van-field
          v-model="hotelDetails.appliance[0].name"
          name="appliance"
          label="电器设施"
          placeholder="电器设施"
        />
        <van-field
          v-model="hotelDetails.basics[0].name"
          name="basics"
          label="基础设施"
          placeholder="基础设施"
        />
        -->



      <div style="margin: 16px">
        <van-button round block color="#601287" native-type="submit">
          {{ $t("manageHShop.submmit") }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<style lang="scss" scoped>
.hotelMerchandise {
  width: 100vw;
  min-height: 100vh;
  background-color: #f0f0f0;
  padding: 20px;
  box-sizing: border-box;

  .back {
    margin: 10px 0;
  }

  .imge {
    padding: 5px;
    background-color: #fff;
    margin: 10px 0;
    min-height: 200px;

    p {
      font-size: 18px;
      margin: 5px 0;
    }
  }

  .basicsList {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;

    .item {
      border: 1px solid #e2e2e2;
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
      align-items: center;
      padding: 10px;
      margin: 10px;

      .imges {
        width: 50px;
        height: 50px;
        overflow: hidden;

        img {
          width: 100%;
        }
      }

      p {
        font-size: 18px;
      }

      &.con {
        border: 1px solid #1a90bf;
      }
    }

    .btn {
      text-align: center;
      width: 100%;
      font-size: 18px;

      div {
        height: 40px;
        width: 120px;
        margin: 10px auto;
        line-height: 40px;
        background-color: #601287;
        color: #fff;
        border-radius: 10px;
      }
    }
  }
}
</style>